<template>
  <div>
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>信息管理</el-breadcrumb-item>
      <el-breadcrumb-item><b>公告管理</b></el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <!--添加按钮  -->
  <div>
    <el-button type="success" @click="dialogAddState=true" >
      <el-icon><Plus /></el-icon>  添加
    </el-button>
    <el-button type="danger"   @click="deleteSelectedRows()">
      <el-icon><Delete /></el-icon>  批量删除
    </el-button>
  </div>
  <!--  数据表格-->
  <div style="margin:20px">
    <el-table :data="noticeInfo" stripe border style="width: 100%"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id"  width="55px" v-if="show">
        <template #default="{ row }">
          <!-- 根据状态改变文本颜色 -->
          <span :class="statusClass(row.id)">
              {{ row.id }}
            </span>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" width="80px"/>
      <el-table-column prop="content" label="详情"   width="500px" />
      <el-table-column prop="publishdt" label="发布时间" />
      <el-table-column prop="identity" label="发布人" />
      <el-table-column prop="reason" label="理由" />
      <el-table-column prop="ispublic" label="状态" >
        <template #default="{ row }">
          <!-- 根据状态改变文本颜色 -->
          <span :class="statusClass(row.ispublic)">
              {{ row.ispublic }}
            </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px" align="center">
        <template #default="{ row }">
          <!-- 操作按钮 -->
          <el-button
              type="success"
              size="default"
              :disabled="approveDisabledMap[row.id]"
              @click="approveAudit(row)"
          >
            <el-icon><CircleCheck /></el-icon>同意
          </el-button>
          <el-button
              type="danger"
              size="default"
              :disabled="rejectDisabledMap[row.id]"
              @click="rejectAudit(row)"
          >
            <el-icon><CircleClose /></el-icon>拒绝
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!--添加 -->
  <el-dialog v-model="dialogAddState" title="添加公告" width="380">
    <div>
      <el-form ref="formAddRef" :rules="formAddRules" :model="formAdd" label-width="120px">
        <el-form-item prop="title" label="标题">
          <el-input v-model="formAdd.title" maxlength="6" show-word-limit></el-input>
        </el-form-item>
        <el-form-item prop="content" label="内容">
          <el-input v-model="formAdd.content" type="textarea" ></el-input>
        </el-form-item>
        <el-form-item prop="identity">
          <el-input v-model="formAdd.identity" v-show="show" ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogAddOnReset">取消</el-button>
        <el-button type="primary"  @click="dialogAddOnSubmit" >确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!--  分页-->
  <div class="page">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3,4]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>
<script setup>
import {ArrowRight, Delete, CircleCheck, CircleClose, Plus} from '@element-plus/icons-vue'
import {onMounted, reactive, ref} from "vue";
import request from "../../../utils/freshman";
import {ElMessage, ElMessageBox} from "element-plus";
onMounted(()=>{
  initInfo();
  getNotice();
})
const userInfo=reactive({})
const initInfo=()=>{
  const loginUser = sessionStorage.getItem("loginUser");
  if (loginUser) {
    const userobj = JSON.parse(loginUser)
    userInfo.aname=userobj.aname;

    formAdd.identity=userInfo.aname;
  }
}
//分页
const currentPage = ref(1)
const pageSize = ref(3)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
let totals=ref(0);
const noticeInfo=ref([])
const getNotice=()=>{
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    orderBy:1,
    // 初始时不包含其他参数
  };
  request({
    url:'/notice/all',
    method:'get',
    params,
  }).then((req)=>{
    if (req.data.errorCode==200){
      noticeInfo.value=req.data.data.records;
      totals.value=req.data.data.total;
      noticeInfo.value.forEach((item) => {
        if(item.ispublic == "同意"){
          approveDisabledMap[item.id] = true;
          rejectDisabledMap[item.id] = true;
        }else if (item.ispublic == "拒绝") {
          approveDisabledMap[item.id] = true;
          rejectDisabledMap[item.id] = true;
        }else if(item.ispublic == "未审核"){
          approveDisabledMap[item.id] = false;
          rejectDisabledMap[item.id] = false;
        }
      });
    }
  })
}
const handleSizeChange = (val) => {
  pageSize.value=val;
  getNotice()
}
const handleCurrentChange = (val) => {
  currentPage.value=val;
  getNotice()
}

// 同意和拒绝按钮的禁用状态映射
const approveDisabledMap = reactive({});
const rejectDisabledMap = reactive({});
const statusClass = (ispublic) => {
  switch (ispublic) {
    case '未审核':
      return 'status-normal';
    case '同意':
      return 'status-delayed';
    case '拒绝':
      return 'status-cancelled';
    default:
      return '';
  }
};

const approveAudit = (row) => {
  // 模拟同意审核操作
  request({
    url:'/admin/approve',
    method:'get',
    params:{
      id: row.id
    }
  }).then(req=>{
    if (req.data.errorCode==200){
      ElMessage.success("审核通过");
      row.ispublic="同意";
      getNotice();
    }
  })
};

const rejectAudit = (row) => {
  // 模拟拒绝审核操作
  request({
    url:'/admin/reject',
    method:'get',
    params:{
      id: row.id
    }
  }).then(req=>{
    if (req.data.errorCode==200){
      ElMessage.success("审核未通过");
      row.ispublic="拒绝";
      getNotice();
    }
  })
};


///////////////////////添加
const dialogAddState = ref(false)
const formAddRules={
  title: [
    { required: true, message: '请输入哪栋楼', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5]+$/, message: '只能输入汉字', trigger: 'blur' },
    { max: 8, message: '长度不能超过8个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ]
};
// 新增表单引用
const formAddRef = ref()
// 新增表单初始化数据
const formAddData = {
  title:'',
  content:'',
  identity:'',
  type:1,
}
// 新增表单绑定数据模型
const formAdd = reactive({...formAddData})   // ...formAddData 解构formAddData
const dialogAddOnSubmit = () => {
  request({
    method:'post',
    url:'/notice/add',
    params:formAdd,
  }).then(req=>{
    if (200 == req.data.errorCode){
      ElMessage({
        type:'success',
        message:req.data.msg
      })
      Object.assign(formAdd , formAddData)
      getNotice();
    }
  })
  dialogAddState.value=false;
}
const dialogAddOnReset = () => {
  // 清空表单数据
  Object.assign(formAdd , formAddData)
  // 关闭对话框
  dialogAddState.value = false
}
//删除多个
const selectedRows=ref([])
const handleSelectionChange=(rows)=>{
  selectedRows.value = rows;
}
const deleteSelectedRows=()=>{
  if (selectedRows.value.length == 0) {
    ElMessage({
      message: '请选择要删除的记录',
      type: 'warning',
    });
    return;
  }

  ElMessageBox.confirm(
      '此操作将永久删除选中的记录, 是否继续?',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        // 获取所有选中的ID
        const ids = selectedRows.value.map(row => row.id).join(',');
        request({
          method: 'delete',
          url: '/notice/dels',
          params:{id:ids}
        }).then((response) => {
          console.log(response)
          if (response.data.errorCode == 200) {
            ElMessage({
              type: 'success',
              message: '批量删除成功',
            });
            getNotice();
          }
        }).catch(() => {
          ElMessage({
            type: 'error',
            message: '批量删除失败',
          });
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        });
      });
};
</script>
<style scoped>
.el-breadcrumb{
  font-size: 18px;
  margin: 20px;
}
.page{
  margin-left: 30%;
}
.status-normal {
  color: blue;
}

.status-delayed {
  color: green;
}

.status-cancelled {
  color: red;
}
</style>